package com.github.mall.common.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;


@UtilityClass
public class PasswordUtil {

    public String getPassword(String userName, String password) {
        byte[] key = PasswordUtil.getKey(userName);
        SymmetricCrypto des = new SymmetricCrypto(SymmetricAlgorithm.DESede, key);
        return des.encryptHex(password);
    }

    public boolean verifyPassword(String userName, String password, String inputPassword) {
        byte[] key = PasswordUtil.getKey(userName);
        SymmetricCrypto des = new SymmetricCrypto(SymmetricAlgorithm.DESede, key);
        String decryptStr = des.decryptStr(password, CharsetUtil.CHARSET_UTF_8);
        return StrUtil.equals(inputPassword, decryptStr);
    }

    @SneakyThrows
    public byte[] getKey(String userName) {
        StringBuilder stringBuilder = new StringBuilder();
        while (true) {
            if (stringBuilder.toString().getBytes().length >= 24) {
                break;
            }
            stringBuilder.append(userName);
        }
        byte[] bytes = stringBuilder.toString().getBytes("utf-8");
        return SecureUtil.generateKey(SymmetricAlgorithm.DESede.getValue(),bytes).getEncoded();
    }


}
